import psutil
import datetime
import time
import json
from tkinter import Tk
from tkinter import messagebox
from playsound import playsound


def get_now_time(yon):
    if yon:
        return '当前本地时间：' + time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
    else:
        return '当前本地时间:未开启检测'


def get_battery(yon):
    if yon:
        battery_info = []
        battery = psutil.sensors_battery()
        plugged = battery.power_plugged
        percent = str(battery.percent)
        battery_info.append('当前电量百分比为：' + percent + '%')
        if not plugged:
            plugged_status = "否"
        else:
            plugged_status = "是"
        battery_info.append('是否接入电源：' + plugged_status)
        return '\n'.join(battery_info)
    else:
        return '电池信息:未开启检测'


def get_cpu(yon):
    if yon:
        cpu_list = [
            u"物理CPU个数: %s" % psutil.cpu_count(logical=False),
            u"cpu使用率: %s" % (str(psutil.cpu_percent(1))) + '%'
        ]
        return '\n'.join(cpu_list)
    else:
        return 'CPU信息:未开启检测'


def get_memory(yon):
    if yon:
        free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
        total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
        memory = int(psutil.virtual_memory().total -
                     psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
        memory_list = [
            "物理内存： %s G" % total,
            u"剩余物理内存： %s G" % free,
            u"物理内存使用率： %s %%" % int(memory * 100)
        ]
        return '\n'.join(memory_list)
    else:
        return '内存信息:未开启检测'


def get_boot_time(yon):
    if yon:
        return "系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    else:
        return '系统启动时间:未开启检测'


def get_user_info(yon):
    if yon:
        users_count = len(psutil.users())
        users_list = ",".join([u.name for u in psutil.users()])
        return "当前有%s个用户，是 %s" % (users_count, users_list)
    else:
        return '用户信息:未开启检测'


def get_net_info(yon):
    if yon:
        net = psutil.net_io_counters()
        bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
        bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
        return "网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent)
    else:
        return '网卡信息:未开启检测'


def get_disk_info(yon):
    if yon:
        io = psutil.disk_partitions()
        disk_info = ['---------------------磁盘信息---------------------']
        device_number = len(io)
        disk_info.append('目前有' + str(device_number) + '个盘，是' + ','.join([i.device[:-2] + '盘' for i in io]))
        for i in io:
            o = psutil.disk_usage(i.device)
            disk_info.append(str(i.device)[:-2] + "盘总容量：" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
            disk_info.append(str(i.device)[:-2] + "盘已用容量：" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
            disk_info.append(str(i.device)[:-2] + "盘可用容量：" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")
        return '\n'.join(disk_info)
    else:
        return '磁盘信息:未开启检测'


def get_process_info(yon):
    if yon:
        process_info = ['---------------------进程信息---------------------']
        for pnum in psutil.pids():
            p = psutil.Process(pnum)
            process_info.append(u"进程名 %-20s  内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s "
                                % (p.name(), p.memory_percent(), p.status(), p.create_time()))
        return '\n'.join(process_info)
    else:
        return '进程信息:未开启检测'


class Checker(object):
    """
    检查系统状态
    """

    def __init__(self):
        self.check_result_list = []
        try:
            with open('./src/its-up_settings.json', 'rb') as f:
                settings = json.loads(f.read())
                for key in settings.keys():
                    self.check_result_list.append(eval(key)(settings[key]))
            self.final_result = u'自动检查已完成。\n' + '\n'.join(self.check_result_list)
        except Exception as e:
            messagebox.showerror(title='读取错误', message='发生读取错误！读取配置文件（its-up_settings.json）失败！\n---错误信息---\n'+str(e))

    def get_content(self):
        return self.final_result


class Main(object):
    def __init__(self):
        self.root = Tk()
        self.root.withdraw()
        self.content = Checker()
        try:
            self.root.iconbitmap('./src/itsup.ico')
        except Exception as e:
            messagebox.showerror(title='读取错误', message='发生读取错误！读取图标文件（itsup.ico）失败！\n---错误信息---\n'+str(e))
        try:
            self.sound_touxi = playsound('./src/touxi.mp3')
        except Exception as e:
            messagebox.showerror(title='读取错误', message='发生读取错误！读取偷袭老同志音频文件（touxi.mp3）失败！\n---错误信息---\n'+str(e))
        try:
            self.sound_wude = playsound('./src/wude.mp3')
        except Exception as e:
            messagebox.showerror(title='读取错误', message='发生读取错误！读取武德音频文件（wude.mp3）失败！\n---错误信息---\n'+str(e))
        try:
            messagebox.showinfo(message='起来了啊！起来了啊！电脑已成功启动！正在执行自动检查……', title='电脑已成功启动')
        except Exception as e:
            messagebox.showerror(title='未知错误', message='发生未知错误！'+str(e))
        try:
            messagebox.showinfo(title='自动检查', message=self.content.get_content())
        except Exception as e:
            messagebox.showerror(title='运行错误', message='发生运行错误！执行自动检查失败！\n---错误信息---\n'+str(e))


if __name__ == '__main__':
    Main()
